package com.ujs.code.zqh;

public class one {

    // 判断一个数是否为素数
    private static boolean isPrime(int num) {
        if (num <= 1) {
            return false;
        }
        if (num <= 3) {
            return true;
        }
        if (num % 2 == 0 || num % 3 == 0) {
            return false;
        }
        for (int i = 5; i * i <= num; i += 6) {
            if (num % i == 0 || num % (i + 2) == 0) {
                return false;
            }
        }
        return true;
    }

    // 递归生成排列并计数
    private static int countValidPermutations(int[] permutation, int index) {
        if (index == permutation.length) {
            return 1; // 找到一个满足条件的排列
        }
        int count = 0;
        for (int i = 1; i <= permutation.length; i++) {
            boolean used = false;
            for (int j = 0; j < index; j++) {
                if (permutation[j] == i) {
                    used = true;
                    break;
                }
            }
            if (!used) {
                // 检查是否满足相邻元素之和不是素数
                if (index == 0 || !isPrime(permutation[index - 1] + i)) {
                    permutation[index] = i;
                    count += countValidPermutations(permutation, index + 1);
                }
            }
        }
        return count;
    }
    public static void main(String[] args) {
        int n = 6;
        int[] permutation = new int[n];
        int count = countValidPermutations(permutation, 0);
        System.out.println("长度为 " + n + " 的排列满足条件的数量为: " + count);
    }
}
